#!/usr/bin/python
#coding=utf-8

import logging
import json
import curl
import time
import commands
import os
import sys 
import tempfile

def usage():
    print """
Parking Version 0.1 rewritten in python by http://wushituichao.cn/
Original version is written in php by http://www.onemouse.cn/
Usage: python parking.py -u <user> -p <password> | -h | -t | -l
  -u  your kaixin001.com's user
  -p  your kaixin001.com's password
  -h  print help info
  -t  parking your cars
  -l  show your cars info
"""

def getUserData(cookies):
    logging.debug('cookies: ' + cookies)
    userUrl = 'http://www.kaixin001.com/app/app.php?aid=1040'
    data = curl.getUrlEx(userUrl, False, cookies)
    begin = 'var v_userdata = '
    middle = 'var v_frienddata = '
    end = 'var today = new Date();'
    beginPos = data.find(begin)
    middlePos = data.find(middle, beginPos + len(begin))
    endPos = data.find(end, middlePos + len(middle))

    me = data[beginPos + len(begin) : middlePos + len(begin) - len(middle)]
    friends = data[middlePos + len(middle) : endPos + len(middle) - len(end) + 1]

    key = 'var g_verify = "'
    end = '";'
    beginPos = data.find(key, endPos)
    endPos = data.find(end, beginPos + len(key))
    verify = data[beginPos + len(key) : endPos]

    beginTag = '<script language=javascript>'
    endTag = '</script>\r\n\r\n<script language=javascript>'
    begin = data.find(beginTag, beginPos-100) + len(beginTag)
    end = data.find(endTag, begin)
    javascript = data[begin : end]
    javascript += ' print(acc());'
    javascript = javascript.replace('\n', '').replace('\r', '')

    fd, fn = tempfile.mkstemp()
    fh = os.fdopen(fd, 'w')
    fh.write(javascript)
    fh.close()
    status, acc = commands.getstatusoutput('/usr/bin/js ' + fn)
    if status != 0:
        logging.info('Cannot execute "js", plz install spidermonkey first')
        sys.exit(2)

    return {'cars':json.read(me), 
            'friends':json.read(friends), 
            'verify':verify,
            'acc':acc,
            }

def getFriendParkingInfo(cookies, uid, verify):
    data = {'puid':uid, 'verify':verify}
    url = 'http://www.kaixin001.com/parking/user.php'
    data = curl.getUrlEx(url, data, cookies)
    return json.read(data)

def parkCarToFriendParking(cookies, carid, first_fee_parking, neighbor, park_uid, parkid, verify, acc):
    url = 'http://www.kaixin001.com/parking/park.php'
    data = {
            'carid':carid,
            'first_fee_parking':first_fee_parking,
            'neighbor':neighbor,
            'park_uid':park_uid,
            'parkid':parkid,
            'verify':verify,
            'acc':acc,
            }
    result = curl.getUrlEx(url, data, cookies)
    logging.debug('For parking, post:' + str(data))
    logging.debug('kaixin returns:' + str(result))
    return json.read(result)

def getFriendEmptyParking(cookies, friends, verify):
    all = []
    for v in friends:
        '''
            full = 0 : 有非免费车位可停车(无图标)
            full = 1 : 无车位可停车(满图标)
            full = 2 : 有免费车位可停车(半满图标)
        '''
        if v['full'] == '0':
            all.append(v)
    
    logging.debug('有非免费空车位的朋友: '+str(all))

    data = {}
    for v in all:
        data[v['uid']] = getFriendParkingInfo(cookies, v['uid'], verify)

    #logging.debug('data:' + str(data))

    empty = {}
    for (k,v) in data.items():
        for vv in v['parking']:
            if vv['car_uid'] == 0:
                if not empty.has_key(k):
                    empty[k] = {}
                if not empty[k].has_key('parking'):
                    empty[k]['parking'] = []

                empty[k]['parking'].append(vv)

        if empty.has_key(k):
            empty[k]['user'] = v['user']

    #logging.debug('empty:' + str(empty))
    return empty

def showUserInfo(user, cars):
    if not user:
        usage()
        sys.exit(2)

    count = len(cars)
    cash = 0
    print '您是 <', user['real_name'], '>'
    print '您有 <', count, '> 辆车'
    print '  分别是: '
    for v in cars:
        print '  <', v['car_name'],'> : <', v['price'], '.00> RMB, 目前停在 <', v['park_real_name'], '> 的车位上'
        cash += int(v['price'])

    print '目前您共有 <', user['cash'], '.00> RMB'
    print '目前您的车共值 <', cash, '.00> RMB'
    print '目前您的身价是 <', (cash + int(user['cash'])), '.00> RMB'

def parking(cookies, user, cars, friends, verify, acc):
    empty = getFriendEmptyParking(cookies, friends, verify)
    #logging.debug('朋友的空车位: ' + str(empty))
    i = 0
    succ = 0
    now = time.time()
    count = len(cars)
    print '开始停车了'
    for (k, v) in empty.items():
        if i >= count:
            break

        car = cars[i]

        #如果和上次停车的用户一致，则跳过这个用户 
        if car['park_uid'] == k:
            continue

        #停车20分钟后再重新停车.
        while car['ctime'] + 20 * 60 > now:
            print '  您的 <', car['car_name'], '> 在 <', car['park_real_name'], '> 的车位 还没有停满 20分钟， 不能换车位'
            i += 1
            if i >= count:
                break
            car = cars[i]

        if i >= count:
            break

        carid = car['carid']
        first_fee_parking = v['user']['first_fee_parking']
        neighbor = v['user']['neighbor']
        #只在一个人的车位上停一辆
        for parking in v['parking']:
            park_uid = k
            parkid = parking['parkid']
            ret = parkCarToFriendParking(cookies, carid, first_fee_parking, neighbor, park_uid, parkid, verify, acc)
            if ret['errno'] == 0:
                print '  成功将车 <', car['car_name'], '> 从 <', car['park_real_name'], '> 的车位 停到 <', v['user']['real_name'], '> 的车位上'
                #记录成功的车辆数
                succ += 1
                #成功后 ，继续停下一辆。
                i += 1
                break
            else:
                print '  将 <', car['car_name'], '> 从 <', car['park_real_name'], '> 的车位 停到 <', v['user']['real_name'], '> 的车位的时候 发生错误'
                print '  错误原因是: ', ret['error']

    print '成功停车 ', succ, ' 辆 '
    return True
